package com.jp.knowledge.activity;


import android.text.TextUtils;
import com.jiayen.util.ToasUtil;
import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.DocBean;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.functions.Func1;

import static java.lang.String.format;


/**
 * 文档读取activity
 */
public class ReadDocActivity extends SlidingActivity implements OnPageChangeListener {

    @ViewInject(R.id.pdfView)
    private PDFView  pdfView;

    private   int pageNumber=1;

    private String pdfName="测试";
    private DocBean docBean;
    @Override
    protected int getResourceId() {
        return R.layout.activity_read_doc;
    }

    @Override
    protected void init() {
        docBean= getIntent().getParcelableExtra("doc");
        initRead();
    }

    /**
     * webView加载
     */
    private void initRead() {
        String url =docBean.getPdfUrl();//"http://h.jp580.com/httpclient-tutorial.pdf";
        if(TextUtils.isEmpty(url))url = "http://h.jp580.com/httpclient-tutorial.pdf";
//        loading.show();
        showBgLoadingDialog();
        HttpHelper.getInstance(mContext).downloadFile(url,new Func1<ResponseBody, String>(){
            @Override
            public String call(ResponseBody body) {
               String filePath =  savePdf(body);//保存pdf文件
                return filePath;
            }
        },new Subscriber<String>(){
            @Override
            public void onCompleted() {
//                loading.cancel();
                cancleBgLoadingDialog();
            }

            @Override
            public void onError(Throwable e) {
//                loading.cancel();
                cancleBgLoadingDialog();
                ToasUtil.toast(mContext,"读取文档失败");
            }

            @Override
            public void onNext(String filePath) {

                pdfView.fromFile(new File(filePath))
                        .defaultPage(pageNumber)
//                        .onPageChange(ReadDocActivity.this)
                        .load();

            }
        });
//        pdfView.fromFile()
    }

    /**
     * 保存pdf文件
     * @param body
     * @return
     */
    private String savePdf(ResponseBody body) {
        String path =  mContext.getCacheDir().getPath()+"/pdf/test.pdf";
        File file = new File(path);
        File parent = file.getParentFile();
        if (!parent.exists()){
            parent.mkdirs();
        }
         InputStream input = body.byteStream();
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len=input.read(buf))!=-1){
                out.write(buf,0,len);
            }
            out.close();
            input.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }


    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(format("%s %s / %s", pdfName, page, pageCount));
    }
}
